package com.macrohard.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.macrohard.admin.service.SysMenuService;
import com.macrohard.mapper.domain.SysMenu;
import com.macrohard.mapper.mapper.SysMenuMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
* @author 27371
* @description 针对表【sys_menu(系统菜单表)】的数据库操作Service实现
* @createDate 2022-07-14 12:32:00
*/
@Service
@RequiredArgsConstructor
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu>
    implements SysMenuService {

	private final SysMenuMapper sysMenuMapper;

	private List<SysMenu> buildTree(List<SysMenu> roots) {
		return roots.stream()
						.filter((item) -> item.getFsign() == 0)
						.peek((menu) -> menu.setChildren(getChildren(menu, roots)))
						.sorted(Comparator.comparingInt(SysMenu::getSign))
						.collect(Collectors.toList());
	}

	private List<SysMenu> getChildren(SysMenu root, List<SysMenu> all) {
		return all.stream()
						.filter(item -> Objects.equals(item.getFsign(), root.getSign()))
						.peek(item -> item.setChildren(getChildren(item, all)))
						.sorted(Comparator.comparingInt(SysMenu::getSign))
						.collect(Collectors.toList());
	}

	@Override
	public List<SysMenu> getAllMenu() {
		List<SysMenu> sysMenus = sysMenuMapper.selectList(Wrappers.emptyWrapper());
		return buildTree(sysMenus);
	}

	@Override
	public List<SysMenu> getMenuWithTeacherRole(Integer tId, Boolean flat) {
		List<SysMenu> sysMenus = sysMenuMapper.selectAllMenuByTId(tId);
		if (flat) {
			return sysMenus;
		}
		return buildTree(sysMenus);
	}
}




